//
//  DDTextFieldEditViewController.m
//  DingDongZP
//
//  Created by Jyh on 16/4/22.
//  Copyright © 2016年 iyhjiang.com. All rights reserved.
//

#import "DDTextFieldEditViewController.h"

#define MAX_STARWORDS_LENGTH   15

@interface DDTextFieldEditViewController () <UITextFieldDelegate>



@end

@implementation DDTextFieldEditViewController

- (void)setMaxCharacterNumber:(NSInteger)maxCharacterNumber
{
    if (_maxCharacterNumber != maxCharacterNumber) {
        _maxCharacterNumber = maxCharacterNumber;
        self.characterNumLabel.text = [NSString stringWithFormat:@"0/%d",(int)self.maxCharacterNumber];
    }
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (instancetype)initWithMaxCharacterNumber:(NSInteger)number
{
    if (self = [super init]) {
        _maxCharacterNumber = number;
    }
    
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = COLOR_BACKGROUND_GRAY;
    if (self.maxCharacterNumber == 0) {
        self.maxCharacterNumber = MAX_STARWORDS_LENGTH;
    }
    
    [self addLeftButtonItemWithImage:[UIImage imageNamed:@"back"] action:@selector(backButtonClick:)];
    [self addRightButtonItemWithImage:[UIImage imageNamed:@"common_nav_ok"] action:@selector(saveButtonClick:)];
    
    self.characterNumLabel.text = [NSString stringWithFormat:@"%d/%d",(int)[self.textField.text length],(int)self.maxCharacterNumber];
    self.textField.placeholder = @"请输入相关信息";
    
    [self setupSubviewLayout];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:UITextFieldTextDidChangeNotification object:self.textField];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.textField becomeFirstResponder];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupSubviewLayout
{
    WEAKSELF
    
    UIView *textFieldBgView = [[UIView alloc] init];
    textFieldBgView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:textFieldBgView];
    [textFieldBgView addSubview:self.textField];
    [self.view addSubview:self.characterNumLabel];
    
    self.textField.delegate = self;
    
    [textFieldBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view);
        make.right.mas_equalTo(weakSelf.view);
        make.top.mas_equalTo(weakSelf.view).offset(15);
        make.height.mas_equalTo(50);
        
    }];
    
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(textFieldBgView.mas_left).offset(10);
        make.right.mas_equalTo(textFieldBgView.mas_right).offset(-10);
        make.top.mas_equalTo(textFieldBgView);
        make.bottom.mas_equalTo(textFieldBgView);

    }];
    
    [self.characterNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view).offset(50);
        make.right.mas_equalTo(weakSelf.view).offset(-10);
        make.top.mas_equalTo(weakSelf.textField.mas_bottom).offset(10);
        make.height.mas_equalTo(20);
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setBlock:(TextBackBlock)block
{
    _block = [block copy];
}

#pragma mark
#pragma mark - Event Response

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    
    [self.view endEditing:YES];
}

- (void)backButtonClick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)saveButtonClick:(UIButton *)button
{
    if (_block) {
        _block(self.textField.text);
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
#pragma mark  UITextFieldDelegate

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//{
//    if ([string isEqualToString:@"\n"]) {
//        return NO;
//    }
//    
//    if (!string.length && range.length > 0) {
//        return YES;
//    }
//    
//    return YES;
//}


-(void)textFiledEditChanged:(NSNotification *)obj{
    UITextField *textField = (UITextField *)obj.object;
    
    NSString *toBeString = textField.text;
    
    NSString *lang = [textField.textInputMode primaryLanguage]; // 键盘输入模式
    
    NSUInteger maxLength = self.maxCharacterNumber; // 上限是10个汉字
    
    if ([lang isEqualToString:@"zh-Hans"]) { // 简体中文输入，包括简体拼音，健体五笔，简体手写
        UITextRange *selectedRange = [textField markedTextRange];
        
        //获取高亮部分
        UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
        
        // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
        if (!position) {
            
            if (toBeString.length > maxLength) {
                
                textField.text = [toBeString substringToIndex:maxLength];
            }
        }
        // 有高亮选择的字符串，则暂不对文字进行统计和限制
        else{
            
        }
    }
    
    // 中文输入法以外的直接对其统计限制即可，不考虑其他语种情况
    else{
        if (toBeString.length > maxLength) {
            
            textField.text = [toBeString substringToIndex:maxLength];
        }
    }
    
    if (!(toBeString.length > self.maxCharacterNumber)) {
        NSUInteger lenth = toBeString.length;
        if (lenth > self.maxCharacterNumber) {
            lenth = self.maxCharacterNumber;
        }
        self.characterNumLabel.text = [NSString stringWithFormat:@"%d/%d",(int)lenth,(int)self.maxCharacterNumber];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    //  如果有过虑条件，执行过虑条件判断输入是否可以通过
    if (self.textFilter) {
        NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
        return self.textFilter(result);
    }
    return YES;
}

#pragma mark
#pragma mark - Getters and Setters

- (UITextField *)textField
{
    if (_textField == nil) {
        _textField = [[UITextField alloc] init];
        _textField.backgroundColor = [UIColor whiteColor];
        _textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (self.value) {
            _textField.text = _value;
        }
    }
    
    return _textField;
}

- (UILabel *)characterNumLabel
{
    if (_characterNumLabel == nil) {
        _characterNumLabel = [[UILabel alloc] init];
        _characterNumLabel.textColor = COLOR_NAVIGATIONBAR;
        _characterNumLabel.font = [UIFont systemFontOfSize:13];
        _characterNumLabel.textAlignment = NSTextAlignmentRight;
    }
    
    return _characterNumLabel;
}

@end
